<template>
  <!-- 异常品工单表单弹窗 -->
  <el-dialog
    v-model="visibleDialog"
    :title="props.title"
    width="1080px"
    draggable
    @close="closeDialog"
    ><el-descriptions
      class="margin-top"
      title=""
      :column="2"
      size="large"
      v-show="props.isReadonly"
      border
    >
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">异常通知单号</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.abnormalCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">状态</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.abnormalStatus }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">填写日期</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.fillDate }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">填写部门</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.fillDepartment }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">填写人</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.filler }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">工序</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.process }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">成品代码</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.materialCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">成品名称</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.materialName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">生产批次</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.productionBatch }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">计划编号</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.planCode }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">异常数量</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.abnormalNum }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">比例</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.abnormalRatio }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">处理结果</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.dealResult }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">判定人</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.judge }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">备注</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.remarks }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">创建时间</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.createTime }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">创建人</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.createdUserName }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">更新时间</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.lastUpdateTime }}
        </div>
      </el-descriptions-item>
      <el-descriptions-item>
        <template #label>
          <div class="cell-item">更新人</div>
        </template>
        <div style="width: 50%; word-break: break-all">
          {{ formData.lastUpdatedUserName }}
        </div>
      </el-descriptions-item>
    </el-descriptions>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-width="160"
      v-show="!props.isReadonly"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="工序" label-width="80px" prop="process">
            <el-select
              style="width: 195px"
              v-model="formData.process"
              placeholder="请选择工序"
              filterable
              clearable
            >
              <el-option
                v-for="item in useDictionary('ProcessType')"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品名称" label-width="80px" prop="materialName">
            <el-select
              style="width: 195px"
              v-model="formData.materialCode"
              placeholder="请选择产品名称"
              filterable
              :filter-method="materialFilter"
              :disabled="formData.process ? false : true"
              @change="changeMaterial"
              clearable
            >
              <el-option
                v-for="item in materialFilteredOptions"
                :key="item.materialCode"
                :label="item.materialName"
                :value="item.materialCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品物料" prop="materialCode" label-width="80px">
            <el-input
              v-model="formData.materialCode"
              placeholder="请输入产品物料"
              clearable
              :disabled="true"
              style="width: 195px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            label="生产批次"
            prop="productionBatch"
            label-width="80px"
          >
            <el-select
              style="width: 195px"
              v-model="formData.productionBatch"
              placeholder="请选择生产批次"
              filterable
              clearable
              :disabled="formData.materialCode ? false : true"
              @change="changeProductionBatch"
            >
              <el-option
                v-for="item in plannedBatchList"
                :key="item.plannedBatch"
                :label="item.plannedBatch"
                :value="item.plannedBatch"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="异常数量" prop="abnormalNum" label-width="80px">
            <el-input
              v-model="formData.abnormalNum"
              placeholder="请输入异常数量"
              clearable
              style="width: 195px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="比例%" prop="abnormalRatio" label-width="80px">
            <el-input
              v-model="formData.abnormalRatio"
              placeholder="请输入比例"
              clearable
              style="width: 195px"
              ><template #suffix><span>%</span></template></el-input
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div
      style="display: flex; justify-content: space-between; align-items: center"
    >
      <h4 v-show="props.isReadonly">问题描述</h4>
      <el-button
        type="success"
        plain
        @click="handleAdd"
        v-show="!props.isReadonly"
      >
        <i-ep-plus />
        新增问题描述
      </el-button>
    </div>
    <div>
      <el-table
        :data="formData.details"
        style="width: 100%"
        :key="Math.random"
        max-height="240px"
        overflow-y="auto"
        border
      >
        <el-table-column type="index" label="序号" align="center" width="100" />
        <el-table-column label="问题描述" props="problemName" min-width="150">
          <template #default="scope">
            <el-select
              style="width: 195px"
              v-model="scope.row.problemCode"
              placeholder="请选择问题描述"
              filterable
              clearable
              @change="changeProblem(scope)"
              v-if="!props.isReadonly"
            >
              <el-option
                v-for="item in problemList"
                :key="item.problemCode"
                :label="item.problemName"
                :value="item.problemCode"
              />
            </el-select>
            <span v-else>{{ scope.row.problemName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="要求" props="problemRequest" min-width="150">
          <template #default="scope">
            <el-input
              v-model="scope.row.problemRequest"
              placeholder="请输入要求"
              clearable
              :disabled="true"
              style="width: 195px"
              v-if="!props.isReadonly"
            />
            <span v-else>{{ scope.row.problemRequest }}</span>
          </template>
        </el-table-column>
        <el-table-column label="实际" props="problemActual" min-width="150">
          <template #default="scope">
            <el-input
              v-model="scope.row.problemActual"
              placeholder="请输入实际"
              clearable
              style="width: 195px"
              v-if="!props.isReadonly"
            />
            <span v-else>{{ scope.row.problemActual }}</span>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          align="center"
          label="操作"
          width="100"
          v-if="!props.isReadonly"
        >
          <template #default="scope">
            <el-button
              type="danger"
              link
              @click.stop="handleDelete(scope.$index)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <h4 v-show="props.isReadonly">产品履历</h4>
      </div>
      <el-table
        v-show="props.isReadonly"
        :data="formData.records"
        style="width: 100%"
        :key="Math.random"
        max-height="240px"
        overflow-y="auto"
        border
      >
        <el-table-column type="index" label="序号" align="center" width="80" />
        <el-table-column
          label="时间"
          props="createTime"
          min-width="180"
          align="center"
        >
          <template #default="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="部门" props="department" min-width="150">
          <template #default="scope">
            {{ scope.row.department }}
          </template>
        </el-table-column>
        <el-table-column label="执行人" props="executor" min-width="100">
          <template #default="scope">
            {{ scope.row.executor }}
          </template>
        </el-table-column>
        <el-table-column
          label="数量"
          props="number"
          min-width="80"
          align="center"
        >
          <template #default="scope">
            {{ scope.row.number }}
          </template>
        </el-table-column>
        <el-table-column
          label="类型"
          props="type"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("abnormalRecordType", scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column
          label="状态"
          props="status"
          min-width="100"
          align="center"
        >
          <template #default="scope">
            {{ useDictionary("abnormalRecordStatus", scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="100">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialogdetail(scope.row)"
              ><i-ep-search />
              详 情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          v-if="!props.isReadonly"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确 定</el-button
        >
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
  <qmsabnormalorder-file-edit
    :visible="addDialog.visible"
    :title="addDialog.title"
    :data="addDialog.data"
    :is-readonly="addDialog.readvisible"
    @change-visible="changeVisible"
  />
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
import { useDictionary } from "@/utils/useTable";
import _ from "lodash-es";
import { validateNumber, validateNumberCanNot1 } from "@/utils/commonHooks";

const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQMSABNORMALORDERADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

const addDialog = reactive<DialogOption>({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
});
function changeVisible(value: boolean) {
  addDialog.visible = value;
  if (!value) {
    addDialog.data = {};
  }
}
function openDialogdetail(roleObj?: any) {
  addDialog.title = "履历附件";
  getInfo(roleObj.id);
  addDialog.readvisible = true;
}

async function getInfo(id: string) {
  request({
    url: `/qms/qmsabnormalorderrecord/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

const rules = reactive({
  abnormalCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  abnormalStatus: [],
  fillDate: [],
  fillDepartment: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  filler: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  process: [
    { required: true, message: "请选择工序", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialCode: [
    { required: true, message: "请选择产品", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  materialName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  productionBatch: [
    { required: true, message: "请选择生产批次", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  planCode: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  abnormalNum: [
    { required: true, message: "请输入数量", trigger: "blur" },
    {
      validator: validateNumberCanNot1,
      trigger: "blur",
    },
  ],
  abnormalRatio: [
    { required: true, message: "请输入比率", trigger: "blur" },

    {
      validator: validateNumber,
      trigger: "blur",
    },
  ],
  dealResult: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  judge: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  remarks: [
    { min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur" },
  ],
  createTime: [],
  createdUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  createdUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  lastUpdateTime: [],
  lastUpdatedUserId: [
    { min: 1, max: 32, message: "长度在 1 到 32 个字符", trigger: "blur" },
  ],
  lastUpdatedUserName: [
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  deleted: [],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "",
  abnormalCode: "",
  abnormalStatus: 0,
  fillDate: "",
  fillDepartment: "",
  filler: "",
  process: "",
  materialCode: "",
  materialName: "",
  productionBatch: "",
  planCode: "",
  abnormalNum: "",
  abnormalRatio: "",
  dealResult: "",
  judge: "",
  remarks: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  deleted: "",
  details: [],
  records: [],
});

watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        abnormalCode,
        abnormalStatus,
        fillDate,
        fillDepartment,
        filler,
        process,
        materialCode,
        materialName,
        productionBatch,
        planCode,
        abnormalNum,
        abnormalRatio,
        dealResult,
        judge,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
        details,
        records,
      } = newVal;
      Object.assign(formData, {
        id,
        abnormalCode,
        abnormalStatus,
        fillDate,
        fillDepartment,
        filler,
        process,
        materialCode,
        materialName,
        productionBatch,
        planCode,
        abnormalNum,
        abnormalRatio,
        dealResult,
        judge,
        remarks,
        createTime,
        createdUserId,
        createdUserName,
        lastUpdateTime,
        lastUpdatedUserId,
        lastUpdatedUserName,
        deleted,
        details,
        records,
      });
      formData.process = String(formData.process);
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = "";
  formData.abnormalCode = "";
  formData.abnormalStatus = 0;
  formData.fillDate = "";
  formData.fillDepartment = "";
  formData.filler = "";
  formData.process = "";
  formData.materialCode = "";
  formData.materialName = "";
  formData.productionBatch = "";
  formData.planCode = "";
  formData.abnormalNum = "";
  formData.abnormalRatio = "";
  formData.dealResult = "";
  formData.judge = "";
  formData.remarks = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
  formData.deleted = "";
  formData.details = [];
  formData.records = [];
}

const loading = ref(false);

/** 异常品工单保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/qms/qmsabnormalorder/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}
const problemList: any = ref([]);
const getProblemList = async () => {
  const { data } = await request({
    url: "/qms/qmsabnormalproblem/getList",
    method: "post",
    data: {},
  });
  problemList.value = data;
};

function changeProblem(row: any) {
  var problem: any = problemList.value.find(
    (item: any) => item.problemCode == row.row.problemCode
  );
  formData.details[row.$index].problemName = problem.problemName;
  formData.details[row.$index].problemRequest = problem.problemRequest;
}

const materialList = ref([]);
const plannedBatchList = ref([]);

const getMaterialList = async () => {
  const { data } = await request({
    url: "/mes/mesplanworkingform/getGroup",
    method: "post",
    data: {
      groupType: 1,
      formStatus: 2,
      processesClassification: formData.process,
    },
  });
  materialList.value = data;
  materialFilteredOptions.value = data;
};

const materialFilteredOptions = ref<any>([]);

// 使用 debounce 包装过滤方法
const materialFilter = _.debounce((query: any) => {
  if (!query) {
    materialFilteredOptions.value = [...materialList.value];
    return;
  }
  materialFilteredOptions.value = materialList.value.filter((option: any) =>
    option.materialName.toLowerCase().includes(query.toLowerCase())
  );
}, 300);

const changeMaterial = (materialCode: String) => {
  const materialDTO: any = materialList.value.find(
    (material: any) => material.materialCode == materialCode
  );
  if (materialDTO) {
    formData.materialName = materialDTO.materialName;
  }
  getPlannedBatchList();
};

const getPlannedBatchList = async () => {
  const { data } = await request({
    url: "/mes/mesplanworkingform/getGroup",
    method: "post",
    data: {
      groupType: 2,
      formStatus: 2,
      processesClassification: formData.process,
      materialCode: formData.materialCode,
    },
  });
  plannedBatchList.value = data;
};

function changeProductionBatch(plannedBatch: String) {
  var group2: any = plannedBatchList.value.find(
    (item: any) => item.plannedBatch == plannedBatch
  );
  if (group2) {
    formData.planCode = group2.processingOrderNumber;
  }
}

/** 添加行 */
const handleAdd = () => {
  let detail: any = {
    problemCode: "",
    problemName: "",
    problemRequest: "",
    problemActual: "",
  };
  formData.details.push(detail);
};

const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
};

onMounted(() => {
  getMaterialList();
  getProblemList();
  getPlannedBatchList();
});
// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});
</script>
